<?php
/**
 * Created by PhpStorm.
 * User: syzhou
 * Date: 2019/1/24
 * Time: 11:08
 */

/**
 * 获取 MySQL 数据库连接
 * @param $params array 连接参数，包括以下键
 * host 主机地址,必须
 * port 服务器端口，可选
 * dbname 数据库名，可选
 * charset 连接所用字符集，可选，默认为 utf8
 * username 用户名，可选
 * password 密码，可选
 * @param $options array 驱动选项，可选，默认属性如下：
 *     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
 *     PDO::ATTR_AUTOCOMMIT => 0
 * @return PDO
 */
function getConnection(array $params, array $options = null)
{
    $dsn = "mysql:host=" . $params['host'];
    if (isset($params['port'])) {
        $dsn .= ';port=' . $params['port'];
    }
    if (isset($params['dbname'])) {
        $dsn .= ';dbname=' . $params['dbname'];
    }
    $charset = isset($params['charset']) ? $params['charset'] : 'utf8';
    $dsn .= ";charset=$charset";
    $username = isset($params['username']) ? $params['username'] : null;
    $password = isset($params['password']) ? $params['password'] : null;
    $default_options = [
        PDO::ATTR_TIMEOUT => 5,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_AUTOCOMMIT => 0
    ];
    if ($options === null) {
        $options = $default_options;
    }
    $conn = new PDO($dsn, $username, $password, $options);
    return $conn;
}


class DbManager {
    private $dbParams;

    /**
     * @var PDO
     */
    private $pdo;

    public function __construct($dbParams)
    {
        $this->dbParams = $dbParams;
    }

    public function setDbParams($dbParams) {
        $this->closeConnection();
        $this->dbParams = $dbParams;
    }

    /**
     * 获取数据库连接
     * @return \PDO 返回 null 代表失败
     */
    public function getConnection() {
        if ($this->pdo !== null) {
            return $this->pdo;
        }
        try {
            $this->pdo = getConnection($this->dbParams);
            $this->pdo->query('select 1')->closeCursor();
        } catch (Exception $e) {
            $this->pdo = null;
        }
        return $this->pdo;
    }

    public function closeConnection() {
        $this->pdo = null;
    }
}